package com.lanou.bookstore.user.service;

import com.lanou.bookstore.user.dao.UserDao;
import com.lanou.bookstore.user.dao.UserDaoImpl;
import com.lanou.bookstore.user.domain.User;

import java.util.List;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();

    @Override
    public boolean registCheck(User user) throws Exception{

        String regex = "[　*| *|　*|//s*]*";
        String s1 = user.getUsername().replaceAll(regex, "");
        String s2 = user.getPassword().replaceAll(regex, "");
        String s3 = user.getEmail().replaceAll(regex, "");

        if (s1 != null && s2 != null && s3 != null){
            List<User> byUsername = userDao.findByUsername(user);
            List<User> byEmail = userDao.findByEmail(user);
            if (byEmail.size() == 0 && byUsername.size() == 0){

                userDao.add(user);
                return true;
            }else if(byUsername.size() != 0 && byEmail.size() != 0){
                throw new Exception("用户名和邮箱都已被注册!");
            }else if (byUsername.size() != 0){
                throw new Exception("用户名已被注册!");
            }else if (byEmail.size() != 0){
                throw new Exception("邮箱已被注册!");
            }
        }else {
            return false;
        }

        return false;
    }

    @Override
    public boolean loginCheck(User user) {

        String regex = "[　*| *|　*|//s*]*";
        String s1 = user.getUsername().replaceAll(regex, "");
        String s2 = user.getPassword().replaceAll(regex, "");


        if (s1.length() != 0 && s2.length() != 0 ){
            List<User> list = userDao.query(user);

            if (list.size() != 0){
                return true;
            }
        }else {
            return false;
        }

        return false;
    }

    @Override
    public void add(User user) {
        userDao.add(user);
    }

}
